<script setup lang="ts">
import { computed, onMounted, reactive, Ref, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { Dialog, Toast } from "vant";
import type { Router } from "vue-router";
import type { ComputedRef } from "vue";
import type { ConsultIllness, Image } from "@/types/consultTypes/consultTypes.ts";
import type { UploaderProps, UploaderInstance, UploaderResultType, UploaderFileListItem } from "vant";
import type { UploaderAfterRead,UploaderBeforeRead } from "vant/lib/uploader/types";
import useConsultStore from "@/pinia/modules/consultStore/consultStore.ts";
import { timeOptions, flagOptions } from "@/constants/index.ts";

const router: Router = useRouter();

const consultStore = useConsultStore();

const formData = reactive<ConsultIllness>({
   illnessDesc: "",
   illnessTime: undefined,
   consultFlag: undefined,
   pictures: [],
});
const fileList: Ref<UploaderFileListItem[]> = ref<UploaderFileListItem[]>([]);

const disabled: ComputedRef<boolean> = computed<boolean>(() => !formData.illnessDesc || formData.illnessTime === undefined || formData.consultFlag === undefined);

const next = () => {
   consultStore.setIllness(formData);
   router.push({ path: "/user/patient", query: { selectPatient: "true" } });
};


const resetFormData = async () => {
   if (!consultStore.consult.illnessDesc) return;
   const confirm = await Dialog.confirm({ title: "温馨提示", message: "是否恢复之前填写的病情数据?", closeOnPopstate: false }).catch(error => error);
   if (confirm === "cancel") return;
   const { illnessDesc, illnessTime, consultFlag } = consultStore.consult;
   Object.assign(formData, { illnessDesc, illnessTime, consultFlag });

};


const afterRead: UploaderAfterRead = async (fileParams: UploaderFileListItem | UploaderFileListItem[]) => {
   if (Array.isArray(fileParams)) return;
   if (!fileParams.file) return;
   const Data = new FormData();
   Data.append("file", fileParams?.file);
   fileParams.status = "uploading";
   fileParams.message = "上传中···";
   try {
      const result: Image = await consultStore.uploadFile(Data);
      fileParams.status = "done";
      fileParams.message = "上传成功";
      fileParams.url = result.url;
      formData.pictures?.push({ ...result });
   } catch (error: any) {
      fileParams.status = "failed";
      fileParams.message = "上传失败";
      Toast.fail(error.message);
   }
};

const beforeRead:any = (file: File) => {
   if (!file.type.startsWith("image")) return Toast.fail("文件只能上传图片");
   return true;
};

const deleteUpload = (fileParams: UploaderFileListItem) => {
   fileList.value = fileList.value.filter(item => item.url !== fileParams.url);
   formData.pictures = formData.pictures!.filter(item => item.url !== fileParams.url);
};


onMounted(() => {
   resetFormData();
});

</script>

<template>
   <div class="consult-illness-page">
      <NavBar left-text="返回" title="图文问诊" @click-left="$router.back()"></NavBar>
      <div class="illness-tip van-hairline--bottom">
         <img class="img" src="@/assets/avatar-doctor.svg" />
         <div class="info">
            <p class="tit">在线医生</p>
            <p class="tip">请描述你的疾病或症状、是否用药、就诊经历，需要我听过什么样的帮助</p>
            <p class="safe">
               <svg-icon svg-name="safe" />
               <span>内容仅医生可见</span>
            </p>
         </div>
      </div>
      <div class="illness-form">
         <van-field type="textarea" rows="3" placeholder="请详细描述您的病情，病情描述不能为空" v-model="formData.illnessDesc"></van-field>
         <div class="item">
            <p>本次患病多久了?</p>
            <RadioBtn :options="timeOptions" v-model="formData.illnessTime"></RadioBtn>
         </div>
         <div class="item">
            <p>此次病情是否去医院就诊过?</p>
            <RadioBtn :options="flagOptions" v-model="formData.consultFlag"></RadioBtn>
         </div>
         <div class="item illness-img">
            <p>请患者上传图文图片</p>
            <van-uploader upload-text="上传图片" :max-count="6" :max-size="500 * 1024" multiple v-model="fileList" :after-read="afterRead" :before-read="beforeRead" @delete="deleteUpload"></van-uploader>
            <p class="tip">上传内容仅医生可见,最多9张图,最大5MB</p>
         </div>
         <van-button type="primary" block round @click="next" :disabled="disabled">下一步</van-button>
      </div>
   </div>
</template>

<style scoped lang="scss">
.consult-illness-page {
   .illness-tip {
      display: flex;
      padding: 15px;

      .img {
         width: 52px;
         height: 52px;
         border-radius: 4px;
         overflow: hidden;
         margin-top: 10px;
      }

      .info {
         flex: 1;
         padding-left: 12px;

         .tit {
            font-size: 16px;
            margin-bottom: 5px;
         }

         .tip {
            padding: 12px;
            background: var(--cp-bg);
            color: var(--cp-text3);
            font-size: 13px;
            margin-bottom: 10px;
         }

         .safe {
            font-size: 10px;
            color: var(--cp-text3);
            display: flex;
            align-items: center;

            .cp-icon {
               font-size: 12px;
               margin-right: 2px;
            }
         }
      }
   }

   .illness-form {
      padding: 15px;

      .van-field {
         padding: 0;

         &::after {
            border-bottom: none;
         }
      }

      .item {
         > p {
            color: var(--cp-text3);
            padding: 15px 0;
         }
      }

      .illness-img {
         padding-top: 16px;
         margin-bottom: 40px;

         .tip {
            font-size: 12px;
            color: var(--cp-tip);
         }
      }

   }
}
</style>
